﻿using IVBlog.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace IVBlog.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IVBlogContext iVBlogContext;

        public HomeController(ILogger<HomeController> logger,IVBlogContext iVBlog)
        {
            _logger = logger;
            iVBlogContext = iVBlog;
        }

        public void FindType()
        {
            List<Category> categories = iVBlogContext.Category.ToList();
            TempData["Category"] = categories;
        }

        //首页
        public IActionResult Index(int pageIndex = 1, int pageSize = 5)
        {
            try
            {
                List<Article> articles = iVBlogContext.Article.Include("Category").Include("Remark").Where(t => t.Astate == 1).ToList();
                var res = iVBlogContext.Article
                    .Where(t => t.Astate == 1)
                    .OrderBy(p => p.ArticleId)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize)
                    .ToList();
                ViewBag.pageIndex = pageIndex;
                ViewBag.pageSize = pageSize;
                //计算总数
                ViewBag.totalRows = articles.Count;
                //计算共有多少页
                ViewBag.totalPage = Math.Ceiling(articles.Count * 1.0 / pageSize);
                Info info = iVBlogContext.Info.FirstOrDefault();
                ViewBag.Qqgroup = info.Qqgroup;
                FindType();
                return View(res);
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //笔记分类页
        public IActionResult Privacy()
        {
            try
            {
                List<Category> categories = iVBlogContext.Category.ToList();
                ViewBag.CategoryNum = iVBlogContext.Category.Count();
                FindType();
                return View(categories);
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //文章详情页
        public IActionResult Article(int id)
        {
            try
            {
                Article article = iVBlogContext.Article.FirstOrDefault(t => t.ArticleId == id);
                ViewBag.aName = article.Aname;
                ViewBag.aContent = article.Acontent;
                ViewBag.aID = article.ArticleId;
                List<Remark> remarks = iVBlogContext.Remark.Include("Reply").Where(t => t.ArticleId == id && t.Rstate == 1).ToList();
                ViewBag.remarks = remarks;
                FindType();
                return View();
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        [HttpPost]
        //评论提交 RemarkSubmit
        public IActionResult RemarkSubmit(int id,string txtName, string txtEmail, string txtWeb, string txtContent)
        {
            try
            {
                Remark remark = new Remark
                {
                    ArticleId = id,
                    RnickName = txtName,
                    Remail = txtEmail,
                    Rweb = txtWeb,
                    Rcontent = txtContent,
                    Rtime = DateTime.Now,
                    Rstate = 0
                };
                iVBlogContext.Remark.Add(remark);
                iVBlogContext.SaveChanges();
                TempData["state"] = "已提交评论，等待审核中哦(#^.^#)";
                return RedirectToAction("Article", new { id = id });
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }

        }

        [HttpPost]
        //回复提交 Reply
        public IActionResult Reply(int Remarkid,string replyName, string replyEmail, string replyWeb, string replyContent)
        {
            try
            {
                Reply reply = new Reply
                {
                    RemarkId = Remarkid,
                    ReplyNickName = replyName,
                    ReplyEmail = replyEmail,
                    ReplyWeb = replyWeb,
                    ReplyContent = replyContent,
                    ReplyTime = DateTime.Now,
                    ReplyState = 0
                };
                iVBlogContext.Reply.Add(reply);
                iVBlogContext.SaveChanges();
                Remark remark = iVBlogContext.Remark.Where(t => t.RemarkId == Remarkid).FirstOrDefault();
                var aID = remark.ArticleId;
                //TempData["state"] = "已提交评论，等待审核中哦(#^.^#)";
                return RedirectToAction("Article", new { id = aID });
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }

        }

        //点赞
        [HttpPost]
        public IActionResult Like(int id)
        {
            try
            {
                Article article = iVBlogContext.Article.FirstOrDefault(t => t.ArticleId == id);
                article.Likes += 1;
                if (iVBlogContext.SaveChanges()>0)
                {
                    TempData["message"] = "点赞成功o(￣▽￣)ｄ！";
                }
                return RedirectToAction("Article", new { id = id });
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //闲言碎语（动态）页
        public IActionResult Dynamic()
        {
            try
            {
                Info info = iVBlogContext.Info.First();
                List<Dynamic> dynamics = iVBlogContext.Dynamic.Where(t => t.Dstate != 1).ToList();
                ViewBag.info = info;
                ViewBag.ArticleNum = iVBlogContext.Article.Count(t => t.Astate == 1);
                ViewBag.DynamicNum = iVBlogContext.Dynamic.Count(t => t.Dstate == 0);
                ViewBag.RemarkNum = iVBlogContext.Remark.Count(t => t.Rstate == 1);
                FindType();
                return View(dynamics);
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        [HttpPost]
        //动态点赞DLikes
        public IActionResult DLikes(int id)
        {
            try
            {
                Dynamic dynamic = iVBlogContext.Dynamic.FirstOrDefault(t => t.DynamicId == id);
                dynamic.Dlikes += 1;
                if (iVBlogContext.SaveChanges() > 0)
                {
                    return RedirectToAction("Dynamic");
                }
                else
                {
                    TempData["error"] = "点赞失败！";
                    return RedirectToAction("Dynamic");
                }
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        [HttpPost]
        //留言提交DRemarkAdd
        public IActionResult DRemarkAdd(string txtName,string txtEmail,string txtWeb,string txtContent)
        {
            try
            {
                Dremark dremark = new Dremark
                {
                    DrnickName = txtName,
                    Dremail = txtEmail,
                    Drweb = txtWeb,
                    Drcontent = txtContent,
                    Drtime = DateTime.Now,
                    Drstate = 0
                };
                iVBlogContext.Dremark.Add(dremark);
                iVBlogContext.SaveChanges();
                TempData["state"] = "已提交留言，等待审核中哦(#^.^#)";
                return RedirectToAction("Dynamic");
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }

        }


        //类别页
        public IActionResult Type(int id)
        {
            try
            {
                Category category = iVBlogContext.Category.FirstOrDefault(t => t.CategoryId == id);
                ViewBag.Cname = category.Cname;
                ViewBag.Cnums = category.Cnums;
                List<Article> articles = iVBlogContext.Article.Include("Remark").Where(t => t.CategoryId == id && t.Astate == 1).ToList();
                TempData["type"] = category.CategoryId;
                TempData["typeName"] = category.Cname;
                FindType();
                return View(articles);
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //搜索页
        public IActionResult Search()
        {
            try
            {
                return View();
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //文章搜索
        [HttpPost]
        public IActionResult Search(string keyboard)
        {
            try
            {
                List<Article> articles = iVBlogContext.Article.Include("Category").Include("Remark").Where(t => t.Aname.Contains(keyboard) || t.Asynopsis.Contains(keyboard)).ToList();
                TempData["Search"] = "查询结果";
                if (articles.Count<=0)
                {
                    TempData["SearchReult"] = "未搜索到"+ keyboard + "相关信息呢，要不要换一个关键词？(✽ ﾟдﾟ ✽)";
                }
                return View("Index", articles);
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        ////文章类别查询
        //[HttpPost]
        //public IActionResult Type()
        //{
        //    try
        //    {
        //        List<Category> categories = iVBlogContext.Category.ToList();
        //        TempData["Category"] = categories;
        //        return View("_Type");
        //    }
        //    catch (Exception ex)
        //    {
        //        TempData["ErrorMessage"] = ex.Message;
        //        return RedirectToAction("Error", "Error");
        //    }
        //}

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
